﻿using System;
using System.ComponentModel.Composition;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using Reactor.Configuration;
using Reactor.Contracts;
using Reactor.Environment;
using UnityServiceLocator = Microsoft.Practices.Unity.ServiceLocatorAdapter.UnityServiceLocator;

namespace Reactor.Container.Unity
{
    [Export(typeof(ICustomizeReactorInitialization))]
    public class ContainerCustomizer : ICustomizeReactorInitialization
    {
        #region Fields

        private readonly IUnityContainer _unityContainer;
        private IServiceLocator _serviceLocator;

        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="ContainerCustomizer"/> class.
        /// <remarks>Creates a <see cref="UnityContainer"/> instance and passes it to the 
        /// constructor overload that accepts an <see cref="IUnityContainer"/> implementation.</remarks>
        /// </summary>
        public ContainerCustomizer() : this(new UnityContainer()) { }

        /// <summary>
        /// Initializes a new instance of the <see cref="ContainerCustomizer"/> class.
        /// </summary>
        /// <param name="unityContainer">The unity container.</param>
        public ContainerCustomizer(IUnityContainer unityContainer)
        {
            if (unityContainer == null) throw new ArgumentNullException("unityContainer");
            _unityContainer = unityContainer;
        }

        #region Implementation of ICustomizeReactorInitialization

        /// <summary>
        /// Gets or sets the execution order for this initializer. The lower the value, the earlier it will
        /// be executed in a chain of initializers.
        /// </summary>
        /// <value>The execution order.</value>
        public uint ExecutionOrder
        {
            get { return 0; }
        }

        /// <summary>
        /// Initializes Reactor by providing a Windsor based <seealso cref="IServiceRegistrar"/> and <seealso cref="IServiceLocator"/>.
        /// </summary>
        public void InitializeReactor()
        {
            var unityGate = new UnityServiceRegistrar(_unityContainer);

            // Set platform service locator
            if (_serviceLocator == null) _serviceLocator = new UnityServiceLocator(_unityContainer);
            Context.ServiceLocator = _serviceLocator;

            unityGate.RegisterInstance<IServiceRegistrar>(unityGate);
        }

        #endregion
    }
}
